package com.scheduledtasklearn.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import jakarta.annotation.PostConstruct;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.ScheduledFuture;

@Service
public class DynamicTaskService {

    @Autowired
    @Lazy
    private TaskScheduler taskScheduler;

    private final Map<String, ScheduledFuture<?>> tasks = new HashMap<>();

    // 添加动态任务
    public void addTask(String taskId, Runnable task, String cron) {
        removeTask(taskId);  // 移除已有任务

        ScheduledFuture<?> future = taskScheduler.schedule(
                task,
                new CronTrigger(cron, TimeZone.getTimeZone("Asia/Shanghai"))
        );

        tasks.put(taskId, future);
        System.out.println("动态任务添加成功: " + taskId);
    }

    // 移除任务
    public void removeTask(String taskId) {
        ScheduledFuture<?> future = tasks.get(taskId);
        if (future != null) {
            future.cancel(true);
            tasks.remove(taskId);
            System.out.println("动态任务已取消: " + taskId);
        }
    }

    // 示例：启动时添加动态任务
    @PostConstruct
    public void initDynamicTask() {
        addTask("dynamic-report",
                () -> System.out.println("动态报告生成: " + new Date()),
                "0/15 * * * * ?");  // 每15秒执行
    }
}